package com.yydm.serviceacls.service.impl;

import com.yydm.commonutils.R;
import com.yydm.serviceacls.entity.LoginUser;
import com.yydm.serviceacls.entity.Permission;

import com.yydm.serviceacls.entity.User;
import com.yydm.serviceacls.mapper.UserMapper;
import com.yydm.serviceacls.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yydm.serviceacls.utils.JwtUtil;
import com.yydm.serviceacls.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }


        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        List<Permission> permissions = loginUser.getPermissions();
        System.out.println(permissions);
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login"+userId,loginUser);
//        redisTemplate.opsForValue().set("login" + userId, loginUser);
        User user1 = loginUser.getUser();
        //把token响应给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("permissions", permissions);
        map.put("user", user1);
        return R.ok().data(map);
    }
}






